package com.slfx.open.api.filter;

import org.apache.commons.io.IOUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * httpServletRequest 包装类
 * 
 * @ClassName: PostJSONHttpServletRequestWrapper
 */
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {

	private byte[] body; // 报文

	public MyHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);

	}

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		if (body == null) {
			synchronized (BASIC_AUTH) {
				body = IOUtils.toByteArray(super.getInputStream());
			}
			if (body == null) {
				return super.getInputStream();
			}
		}
		final ByteArrayInputStream bais = new ByteArrayInputStream(body);
		return new ServletInputStream() {
			@Override
			public int read() throws IOException {
				return bais.read();
			}

			@Override
			public boolean isFinished() {

				return false;
			}

			@Override
			public boolean isReady() {

				return true;
			}

			@Override
			public int readLine(byte[] b, int off, int len) throws IOException {
				if (len <= 0) {
					return 0;
				}
				int count = 0, c;

				while ((c = read()) != -1) {
					b[off++] = (byte) c;
					count++;
					if (c == '\n' || count == len) {
						break;
					}
				}
				return count > 0 ? count : -1;
			}

			@Override
			public void setReadListener(ReadListener readListener) {
				// TODO Auto-generated method stub
			}
		};
	}

}